import mysql.connector

class BaseDao:
    def __init__(self, host='127.0.0.1', user='root', password='12345678', database='ibai-tools'):
        self.host = host
        self.user = user
        self.password = password
        self.database = database
        self.connection = None

    def connect(self):
        self.connection = mysql.connector.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            database=self.database
        )

    def close(self):
        if self.connection is not None:
            self.connection.close()
            self.connection = None

    # 查询
    def execute_query(self, query, values=None):
        try:
            cursor = self.connection.cursor()
            if values:
                cursor.execute(query, values)
            else:
                cursor.execute(query)
            result = cursor.fetchall()
            self.connection.commit()
            print("执行的SQL语句:", cursor.statement)  # 打印SQL语句
            print(result)
            return result
        except mysql.connector.Error as e:
            print(f"执行查询时发生错误: {e}")
            raise e

    # 增删改
    def execute_sql(self, query, values=None):
        try:
            cursor = self.connection.cursor()
            if values:
                cursor.execute(query, values)
            else:
                cursor.execute(query)
            row_count = cursor.rowcount  # 获取受影响的行数
            self.connection.commit()
            print("执行的SQL语句:", cursor.statement)  # 打印SQL语句
            print("受影响的行数:", row_count)
            return row_count
        except mysql.connector.Error as e:
            print(f"执行查询时发生错误: {e}")
            raise e
